<template>
  <div class="w-[97%] p-[20px] bg-[white] h-[100%] flex flex-col">
    <div class="flex justify-between items-center mb-[20px]">
      <el-button :icon="TopLeft" @click="returnBack">返回</el-button>
      <div class="flex">
        <el-upload
          v-model:file-list="fileList"
          :limit="1"
          :on-change="handleFileChange"
          accept=".doc,.docx"
          :auto-upload="false"
        >
          <el-button type="primary" :icon="RefreshRight" :loading="isUploading"
            >重新上传
          </el-button>
        </el-upload>

        <el-button
          type="primary"
          :icon="Document"
          @click="exportDoc"
          class="ml-[10px]"
          >导出文档</el-button
        >
      </div>
    </div>

    <!-- 文档内容容器 -->
    <div
      ref="docRef"
      class="relative w-[97%] h-[calc(100%-200px)] p-[20px] bg-[#fafaff] rounded-[10px] mt-[20px] border-[1px] border-[#bccafb] border-dashed custom-scrollbar"
      style="overflow-y: auto"
    >
      <div
        class="absolute transform -translate-x-1/2 -translate-y-1/2 top-1/2 left-1/2 text-[20px] flex"
        v-show="isUploading"
      >
        加载中<Loading class="ml-[5px]"></Loading>
      </div>
    </div>
  </div>
</template>

<script setup>
import { TopLeft, RefreshRight, Document } from "@element-plus/icons-vue";
import { useRouter, useRoute } from "vue-router";
import { ref, onMounted, nextTick } from "vue";
import { exportHtmlToDocx } from "@/utils/docx.js";
import { checkresult, submitTask } from "@/api/know.js";
import { ElMessage } from "element-plus";
import Loading from "@/component/loading/index.vue";

onMounted(() => {
  init();
});

const router = useRouter();
const route = useRoute();
const docRef = ref(null);

function returnBack() {
  router.push("/fileStart");
  localStorage.removeItem("fileId");
}

const init = (pid) => {
  const fileId = route.query.fileId;
  localStorage.setItem("fileId", fileId);
  checkresult(pid || fileId).then((res) => {
    if (res.code === 200 && res.data?.paragraphResults) {
      // 延迟到下一次 DOM 更新周期执行，确保 docRef 已挂载
      nextTick(() => {
        renderDocument(res.data.paragraphResults);
      });
    }
  });
};

// 渲染文档内容到容器
function renderDocument(paragraphs) {
  // 增加更严格的校验：确保元素已挂载
  if (!docRef.value || !paragraphs || !paragraphs.length) return;

  // 清空容器（此时已确认 docRef.value 存在）
  docRef.value.innerHTML = "";

  if (!docRef.value || !paragraphs.length) return;

  // 清空容器
  docRef.value.innerHTML = "";

  paragraphs.forEach((paragraph) => {
    // 创建段落容器
    const paragraphDiv = document.createElement("div");
    // 设置段落类名（使用textStyle）
    paragraphDiv.className = paragraph.textStyle;

    // 处理表格类型的内容
    if (paragraph.textType == "2") {
      try {
        const tableData = JSON.parse(paragraph.content);
        if (Array.isArray(tableData) && tableData.length > 0) {
          paragraphDiv.innerHTML = createTableHtml(tableData);
        } else {
          paragraphDiv.textContent = paragraph.content;
        }
      } catch (e) {
        paragraphDiv.textContent = paragraph.content;
      }
    } else {
      // 普通文本内容
      paragraphDiv.textContent = paragraph.content;
    }

    // 添加段落到容器
    docRef.value.appendChild(paragraphDiv);

    // 处理关联文件（kbFiles）
    if (paragraph.kbFiles && paragraph.kbFiles.length > 0) {
      const filesContainer = document.createElement("div");
      filesContainer.className = "kb-files-container"; // 用于样式控制

      paragraph.kbFiles.forEach((file) => {
        const fileDiv = document.createElement("div");
        fileDiv.className = "xxx"; // 按需求使用xxx类名
        // 显示文件名和匹配分数
        fileDiv.textContent = `${file.kbFileName} (匹配度: ${file.score}%)`;
        filesContainer.appendChild(fileDiv);
      });

      docRef.value.appendChild(filesContainer);
    }
  });
}

// 辅助函数：将表格数据转换为HTML表格
function createTableHtml(tableData) {
  let html = `
    <table class="custom-table">
      <tbody>
  `;

  tableData.forEach((row, rowIndex) => {
    html += "<tr>";
    row.forEach((cell) => {
      const tag = rowIndex === 0 ? "th" : "td";
      // 给表头和奇偶行添加不同类名，方便单独设置样式
      const cellClass =
        rowIndex === 0
          ? "table-header"
          : rowIndex % 2 === 0
          ? "table-row-even"
          : "table-row-odd";
      html += `<${tag} class="${cellClass}">${cell}</${tag}>`;
    });
    html += "</tr>";
  });

  html += `
      </tbody>
    </table>
  `;
  return html;
}

function exportDoc() {
  exportHtmlToDocx(docRef.value, "山东移动文档导出.docx");
}
const UseUploadHooks = () => {
  const fileList = ref([]);
  const isUploading = ref(false); // 新增：标记是否正在上传

  function handleFileChange(file) {
    const isLt50M = file.size / 1024 / 1024 < 50;
    if (!isLt50M) {
      ElMessage.error("文件大小不能超过 50M");
      fileList.value = [];
      return;
    }

    // 开始上传，标记状态为 true
    isUploading.value = true;
    submitTask({ file: file })
      .then((res) => {
        if (res.code == 500) {
          isUploading.value = false;
          ElMessage.error(res.message);
          return;
        }
        localStorage.setItem("fileId", res.data.fileId);
        init(res.data.fileId);
      })
      .catch((err) => {
        console.error("上传失败", err);
        ElMessage.error("上传失败，请重试");
      })
      .finally(() => {
        isUploading.value = false;
        fileList.value = [];
      });
  }

  return {
    fileList,
    handleFileChange,
    isUploading,
  };
};
const { fileList, handleFileChange, isUploading } = UseUploadHooks();
</script>

<style>
/* 文档样式 - 对应textStyle */
.Title {
  font-size: 24px;
  font-weight: bold;
  margin: 20px 0;
  text-align: center;
}

.Heading1 {
  font-size: 20px;
  font-weight: bold;
  margin: 16px 0 8px 0;
}

.Heading2 {
  font-size: 18px;
  font-weight: bold;
  margin: 14px 0 7px 0;
  padding-left: 10px;
}

.Normal {
  font-size: 14px;
  line-height: 1.8;
  margin: 8px 0;
  color: #333;
}

.custom-table {
  width: 100%;
  border-collapse: collapse;
  margin: 15px 0;
  font-size: 14px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  overflow: hidden; /* 配合边框圆角 */
}

.custom-table th,
.custom-table td {
  border: 1px solid #d2d6dc;
  padding: 10px 12px;
  text-align: left;
}

/* 表头样式 */
.table-header {
  background-color: #f1f5f9;
  color: #1e293b;
  font-weight: 600;
}

/* 偶数行样式 */
.table-row-even {
  background-color: #ffffff;
}

/* 奇数行样式 */
.table-row-odd {
  background-color: #f8fafc;
}

/*  hover 效果 */
.custom-table tr:hover {
  background-color: #f0f9ff;
}

/* 关联文件容器样式 */
.kb-files-container {
  background-color: #f0f0f0;
  padding: 12px;
  margin: 12px 0;
  font-size: 13px;
  color: #333;
  border-left: 3px solid #ccc;
}
</style>

<style scoped>
:deep(.el-upload-list) {
  display: none !important;
}
</style>
